package com.tdkj.service.shop.impl;

import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.tdkj.dao.shop.IBeanShoppingCartDao;
import com.tdkj.model.shop.BeanGood;
import com.tdkj.model.shop.BeanOrderConsigneeInfo;
import com.tdkj.model.shop.BeanShoppingCart;
import com.tdkj.model.shop.BeanShoppingCartItem;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.BaseService;
import com.tdkj.service.ServiceException;
import com.tdkj.service.shop.IBeanShoppingCartService;

@Component("shoppingCartService")
public class BeanShoppingCartServiceImpl extends BaseService implements
		IBeanShoppingCartService {
	
	private IBeanShoppingCartDao beanShoppingCartDao;
    
	@Resource
	public void setBeanShoppingCartDao(IBeanShoppingCartDao beanShoppingCartDao) {
		this.beanShoppingCartDao = beanShoppingCartDao;
	}

	public IBeanShoppingCartDao getBeanShoppingCartDao() {
		return beanShoppingCartDao;
	}

	@Override
	public BeanShoppingCart getByUserId(Long userId) {
		BeanUser user = beanShoppingCartDao.findById(userId, BeanUser.class);
		BeanShoppingCart bean = user.getShoppingCart();
		if(bean == null || bean.getId() == null){
			bean = new BeanShoppingCart();
			bean.setUser(user);
			beanShoppingCartDao.save(bean);
		}
		return bean;
	}
	
	@Override
	public void addItem(Long userId, Long goodId, Integer quantity) throws ServiceException {
		BeanGood good = beanShoppingCartDao.findById(goodId, BeanGood.class);
		BeanUser user = beanShoppingCartDao.findById(userId, BeanUser.class);
		
		for(BeanShoppingCartItem item : user.getShoppingCart().getItems()){
			if(item.getGood().getId() == goodId){
				throw new ServiceException(item.getGood().getName() + " 已在购物车中啦！！！！");
			}
		}
		
		BeanShoppingCartItem item = new BeanShoppingCartItem();
		item.setGood(good);
		item.setQuantity(quantity);
		item.setAddTime(new Timestamp(System.currentTimeMillis()));
		item.setCart(user.getShoppingCart());
		
		beanShoppingCartDao.save(item);
		user.getShoppingCart().getItems().add(item);
	}
	
	@Override
	public void removeItem(Long itemId) {
		beanShoppingCartDao.delete(itemId, BeanShoppingCartItem.class);
	}

	@Override
	public void addConsigneeInfo(Long userId, BeanOrderConsigneeInfo info) {
		BeanUser user = beanShoppingCartDao.findById(userId, BeanUser.class);
		info.setUser(user);
		beanShoppingCartDao.save(info);
	}

	@Override
	public List<BeanOrderConsigneeInfo> getConsigneeInfosByUserId(Long userId) {
		List<BeanOrderConsigneeInfo> consigneeInfos = beanShoppingCartDao.findById(userId, BeanUser.class).getConsigneeInfos();
		consigneeInfos.size();
		return consigneeInfos;
	}

}
